package forge

import (
	"fmt"
	"io/ioutil"

	yaml "gopkg.in/yaml.v2"
)

// YamlConf the base config on yaml
type YamlConf struct {
	AuthKey []byte           `yaml:"AuthKey"`
	Debug   bool             `yaml:"Debug"`
	PgConf  YamlPostgresConf `yaml:"Postgres"`
}

// YamlPostgresConf the postgresql conf on yaml
type YamlPostgresConf struct {
	HostName    string `yaml:"HostName"`
	Port        int    `yaml:"Port"`
	User        string `yaml:"User"`
	Password    string `yaml:"Password"`
	Dbname      string `yaml:"Dbname"`
	SSLMode     string `yaml:"SSLMode"`
	SSLCert     string `yaml:"SSLCert"`
	SSLKey      string `yaml:"SSLKey"`
	SSLRootCert string `yaml:"SSLRootCert"`
}

// UnmarshalYamlFile unmarshal yaml file
func UnmarshalYamlFile(path string, conf interface{}) error {
	dbuf, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	err = yaml.Unmarshal(dbuf, conf)
	return err
}

// GetDatasource get the connect datasource string
func (ypc YamlPostgresConf) GetDatasource() string {
	var pgDS string
	if ypc.SSLMode == "require" {
		pgDS = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=require sslcert=%s sslkey=%s sslrootcert=%s",
			ypc.HostName,
			ypc.Port,
			ypc.User,
			ypc.Password,
			ypc.Dbname,
			ypc.SSLCert,
			ypc.SSLKey,
			ypc.SSLRootCert,
		)
	} else {
		pgDS = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
			ypc.HostName,
			ypc.Port,
			ypc.User,
			ypc.Password,
			ypc.Dbname,
		)
	}
	return pgDS
}
